package buildervalidator

import (
	"errors"
	"fmt"
	"yunj/pkg/yunj/core/consts"
	"yunj/pkg/yunj/util"

	jsoniter "github.com/json-iterator/go"
	"github.com/worklz/go-validate"
)

type Table struct {
	validate.Validator
	asyncType string // 异步类型
}

func (v *Table) DefineRules() map[string]interface{} {
	return map[string]interface{}{
		"builder_id":         "required",
		"builder_async_type": "required|in:stateCount,count,items,event,export",
	}
}

func (v *Table) DefineTitles() map[string]string {
	return map[string]string{
		"builder_id" + ".required":         "访问错误",
		"builder_async_type" + ".required": "builder_async_type" + "参数缺失",
		"builder_async_type" + ".in":       "builder_async_type" + "参数错误",
	}
}

func (v *Table) DefineScenes() map[string][]string {
	return map[string][]string{
		"AsyncRequest": {"builder_id", "builder_async_type"},
	}
}

func (v *Table) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "AsyncRequest" {
		v.asyncType = fmt.Sprintf("%v", datas["builder_async_type"])
		err = v.checkFilter(datas)
		if err != nil {
			return
		}
		switch v.asyncType {
		case "count":
			datas["pks"] = []any{}
		case "items":
			v.handleDatasByItems(datas)
		}
	}
	return
}

func (v *Table) handleDatasByItems(datas map[string]interface{}) (err error) {
	var page, pageSize any
	if pageRaw, exists := datas["page"]; exists {
		page, _ = util.ToInt(pageRaw)
	}
	if page == 0 {
		page = 1
	}
	datas["page"] = page
	if pageSizeRaw, exists := datas["page_size"]; exists {
		pageSize, _ = util.ToInt(pageSizeRaw)
	}
	if pageSize == 0 {
		pageSize = consts.LIST_PAGE_SIZE
	}
	datas["page_size"] = pageSize
	datas["pks"] = []any{}
	return
}

func (v *Table) checkFilter(datas map[string]interface{}) (err error) {
	filterRaw, exists := datas["filter"]
	if !exists {
		return
	}
	filterStr, ok := filterRaw.(string)
	if !ok {
		err = errors.New("filter参数类型错误")
		return
	}

	var filterData interface{}
	if jsoniter.Unmarshal([]byte(filterStr), &filterData) != nil {
		err = errors.New("filter参数需为json类型字符串")
		return
	}
	return
}
